import "./home.scss"
import { Form, Input, Button, Dialog, } from 'antd-mobile'
import { useSelector, useDispatch } from "react-redux";
import { cartSlice } from "@/store/modules/cartSlice";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useState, useRef } from "react";
import { createRecordApi } from "@/api/modules/record";

function Home() {
    const datas = useSelector(state => state.cart.datas)
    const [searchParams] = useSearchParams()
    const dispatch = useDispatch()
    const [src, setSrc] = useState("")
    const navigate = useNavigate()
    const formRef = useRef()

    const onFinish = (values) => {
        if (datas.length > 0) {
            values.datas = datas;
            if (src != "") {
                values.src = src
                createRecordApi(values).then(res => {
                    if (res.code == 0) {
                        Dialog.alert({
                            confirmText: "确认",
                            content: res.msg,
                            onConfirm: () => {
                                setSrc("");
                                dispatch(cartSlice.actions.clear())
                                formRef.current.resetFields()
                                navigate("/")
                            }
                        })
                    }
                })
            }
            else {
                Dialog.alert({
                    confirmText: "确认",
                    content: "请上传发票"
                })
            }
        }
        else {
            Dialog.alert({
                confirmText: "确认",
                content: "请选择销售产品"
            })
        }
    }
    const onFinishFailed = ({ values, errorFields, outOfDate }) => {
        if (errorFields.length > 0) {
            if (errorFields[0].errors.length > 0) {
                Dialog.alert({
                    confirmText: "确认",
                    content: errorFields[0].errors[0]
                })
            }
        }
    }
    const changeHandler = (e) => {
        // console.log(e.target.files);
        const fr = new FileReader();
        fr.onload = function () {
            setSrc(fr.result)
        }
        fr.readAsDataURL(e.target.files[0])
    }

    return (
        <div className="home">
            <p className="common-title">请录入您的信息</p>
            <Form
                initialValues={{
                    "name": searchParams.get("name") || "",
                    "money": searchParams.get("money") || "",
                    "telephone": searchParams.get("telephone") || ""
                }}
                requiredMarkStyle='none'
                layout='horizontal'
                ref={formRef}
                footer={
                    <Button block type='submit' color='primary' size='large' >
                        提交
                    </Button>
                }
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
            >

                <Form.Item
                    name='money'
                    label='销售金额:'
                    rules={[{ required: true, message: '请填写金额' }]}
                >
                    <Input placeholder='请输入销售金额' />
                </Form.Item>
                <Form.Item
                    name='name'
                    label='客户姓名:'
                    rules={[{ required: true, message: '请填写姓名' }]}
                >
                    <Input placeholder='请输入客户姓名' />
                </Form.Item>
                <Form.Item
                    name='telephone'
                    label='客户电话:'
                    rules={[{ required: true, message: '请填写正确的手机号码' }]}
                >
                    <Input placeholder='请输入客户电话' />
                </Form.Item>
                <p className="common-title">请选择销售的产品</p>
                <p
                    className="common-select-btn"
                    onClick={() => {
                        const values = formRef.current.getFieldsValue(["money", "name", "telephone"])
                        navigate(`/goods?money=${values.money}&name=${values.name}&telephone=${values.telephone}`)
                    }}
                >
                    {datas.length > 0 && datas.find(item => !item.uncheck) != null ? (
                        datas.map(item => (
                            !item.uncheck &&
                            <span className="item" key={item.name}>{item.name}x{item.num}</span>
                        ))
                    ) : "选择产品"}
                </p>
                <p className="common-title">请上传发票凭证</p>
                <p className="common-select-btn upload">
                    <span>上传图片</span>
                    <input type="file" onChange={(e) => changeHandler(e)} />
                </p>
                <div className="preview">
                    {src ? <img src={src} /> : <></>}
                </div>
            </Form>

        </div>
    )
}

export default Home